#include "Client.h"


Client::Client(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::ClientClass())
{
    ui->setupUi(this);

    m_httpClient = QSharedPointer<QNetworkHttpClient>::create("127.0.0.1", 8080);

    connect(ui->pushButton_send_post, &QPushButton::clicked, this, &Client::slot_sendMessagePost);

    m_uidStr = QUuid::createUuid().toString();
    m_clientName = "client_1";

    initTCPClient();
    
}

Client::~Client()
{
    {  // 离线。。。
        QString data = "offline";
        sendData(data);
    }
    // 需要提前主动断开连接
    disconnect(m_clientSocket, nullptr, this, nullptr);
    m_clientSocket->deleteLater();
    m_reconnectTimer->stop();


    delete ui;
}



void Client::slot_sendMessagePost()
{
    QJsonObject json;
    json["str1"] = ui->lineEdit_message_post->text();
    json["str2"] = ui->lineEdit_message_post_2->text();
    json["uid"] = m_uidStr;
    json["client_name"] = m_clientName;
    QString jsonStr = QJsonDocument(json).toJson(QJsonDocument::Compact);

    QSharedPointer<ResponseContent> rsp = m_httpClient->postJsonSync("/api/postA", jsonStr, 1500, 1);
    if (rsp != nullptr) {
        if (200 == rsp->StatusCode) {
            QJsonParseError error;
            const QJsonDocument& document = QJsonDocument::fromJson(rsp->BodyContent.toUtf8(), &error);
            if (QJsonParseError::NoError == error.error) {
                const QJsonObject& programmerObject = document.object();
                QString str = programmerObject.value("str").toString();

                ui->label_rspMessgae->clear();
                ui->label_rspMessgae->setText(rsp->BodyContent);
            }
        }
        else {
            ui->label_rspMessgae->clear();
            ui->label_rspMessgae->setText("请求异常 " + rsp->ErrorMessage);
        }
    }
}


/// <summary>
/// TCP Client
/// </summary>
void Client::initTCPClient()
{
    m_clientSocket = new QTcpSocket(this);
    m_reconnectTimer = new QTimer(this);
    m_reconnectTimer->setSingleShot(true);  // 单次触发

    connect(m_reconnectTimer, &QTimer::timeout, this, &Client::attemptReconnect);
    connect(m_clientSocket, &QTcpSocket::connected, this, [this]() {
        m_reconnectAttempts = 0; // 重置计数器
        m_reconnectTimer->stop();
        slot_newConnectionClient(); // 正常连接处理
        });
    connect(ui->pushButton_send_TCP, &QPushButton::clicked, this, &Client::slot_sendData);

    m_clientSocket->connectToHost(M_ADDRESS, M_PORT);
}
void Client::sendData(const QString data)
{
    QByteArray protocolData = CustomProtocol::packData(data.toUtf8());
    if (!m_clientSocket || m_clientSocket->state() != QAbstractSocket::ConnectedState) {
        qWarning() << "Socket is not connected";
        return;
    }
    m_clientSocket->write(protocolData);
    m_clientSocket->flush();
}
void Client::slot_newConnectionClient()
{
    m_reconnectAttempts = 0;  // 重置重连计数器
    ui->label_status->setStyleSheet(CONTROL_LAMP_OK);
    connect(m_clientSocket, &QTcpSocket::readyRead, this, &Client::slot_getDataFromServer);
    connect(m_clientSocket, &QTcpSocket::disconnected, this, &Client::slot_disconnectedClient);

    // 上线。。。。
    QString data = "online";
    sendData(data);

    // 重新连接数据接收信号（避免重复连接）
    disconnect(m_clientSocket, &QTcpSocket::readyRead, this, nullptr);
    connect(m_clientSocket, &QTcpSocket::readyRead, this, &Client::slot_getDataFromServer);
}
void Client::slot_getDataFromServer()
{
    if (m_clientSocket->bytesAvailable()) {
        QByteArray data = m_clientSocket->readAll();
        
        bool unpackSuccess = false;
        QByteArray unpacked = CustomProtocol::unpackData(data, unpackSuccess);

        /*static QByteArray buffer;
        buffer.append(data);
        while (buffer.contains('#')) {
            int startIdx = buffer.indexOf('#');
            int endIdx = buffer.indexOf('#', startIdx + 1);

            if (startIdx != -1 && endIdx != -1) {
                QByteArray message = buffer.mid(startIdx, endIdx - startIdx + 1);
                QString messageStr = QString::fromUtf8(message);
                qDebug() << "收到数据:" << messageStr;
                buffer.remove(0, endIdx + 1);
            }
            else {
                break;
            }
        }*/
    }
}
void Client::slot_disconnectedClient()
{
    qDebug() << "未与TCPserver连接";

    ui->label_status->setStyleSheet(CONTROL_LAMP_NG);

    attemptReconnect();
}
void Client::slot_sendData()
{
    QString data = ui->lineEdit_message_TCP->text();
    sendData(data);
}
void Client::attemptReconnect() {
    // 终止旧连接
    if (m_clientSocket->state() != QAbstractSocket::UnconnectedState) {
        m_clientSocket->abort();
    }

    m_clientSocket->connectToHost(M_ADDRESS, M_PORT);

    // 无论成功与否，启动下一次重连检查
    int delaySec = qPow(2, m_reconnectAttempts) * 1000;
    m_reconnectTimer->start(delaySec);

    if (++m_reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
        qWarning() << "达到最大重连次数，停止尝试";
        m_reconnectTimer->stop();
    }
}